package com.wythe.mall.activity;

import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.AppCompatRatingBar;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;

import com.loopj.android.http.RequestParams;
import com.wythe.mall.R;
import com.wythe.mall.adapter.OrderEvaluateListAdapter;
import com.wythe.mall.adapter.PublishPicAndMessAdapter;
import com.wythe.mall.base.BaseActivity;
import com.wythe.mall.intf.OnRequestDataListener;
import com.wythe.mall.model.OrderBean;
import com.wythe.mall.model.UploadBean;
import com.wythe.mall.utils.ApiOkHttp;
import com.wythe.mall.utils.ToastUtil;
import com.yancy.imageselector.ImageSelectorActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import top.yokey.base.bean.OrderEvaluateBean;

public class EvaluateActivity extends BaseActivity implements OrderEvaluateListAdapter.OnItemClickListener, View.OnClickListener {
    public final static int PICK_IMAGE = 4;
    private RecyclerView mainRecyclerView;
    private LinearLayoutCompat storeLinearLayout;
    private AppCompatTextView storeNameTextView;
    private AppCompatRatingBar descRatingBar;
    private AppCompatRatingBar serviceRatingBar;
    private AppCompatRatingBar logisticsRatingBar;
    private AppCompatTextView saveTextView;

    private int positionInt;

    private String orderIdString;
    private OrderEvaluateBean orderEvaluateBean;

    private OrderEvaluateListAdapter mainAdapter;
    private PublishPicAndMessAdapter publishPicAndMessAdapter;
    private List<UploadBean> mLists;
    private List<OrderBean.ItemVoBean> itemVoBeans;
    private String mImageUrls; //图片上传成功保持url
    private int mCurrentPosition;
    private int picNum = 0;
    private int picSize = 0;
    private StringBuffer picUrls = new StringBuffer();
    private String orderNo;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_evaluate);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            itemVoBeans = (List<OrderBean.ItemVoBean>) bundle.getSerializable("list");
            orderNo = bundle.getString("orderNo");
        }
        if (mLists == null) {
            mLists = new ArrayList<>();
            for (int i = 0; i < itemVoBeans.size(); i++) {
                UploadBean uploadBean = new UploadBean();
                uploadBean.setLevel(5);
                uploadBean.setGoodsId(0);
                uploadBean.setOrderItemId(0);
                uploadBean.setCommentImgUrl("");
                uploadBean.setCommentInfo("");
                mLists.add(uploadBean);
            }
        }
        initView();
        initData();
        initEven();
    }


    public void initView() {
        mainAdapter = new OrderEvaluateListAdapter(this, itemVoBeans);
        mainAdapter.setOnItemClickListener(this);
        mainRecyclerView = (RecyclerView) findViewById(R.id.mainRecyclerView);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mainRecyclerView.setLayoutManager(linearLayoutManager);//设置布局管理器
        mainRecyclerView.setAdapter(mainAdapter);
        storeLinearLayout = (LinearLayoutCompat) findViewById(R.id.storeLinearLayout);
        storeNameTextView = (AppCompatTextView) findViewById(R.id.storeNameTextView);
        descRatingBar = (AppCompatRatingBar) findViewById(R.id.descRatingBar);
        serviceRatingBar = (AppCompatRatingBar) findViewById(R.id.serviceRatingBar);
        logisticsRatingBar = (AppCompatRatingBar) findViewById(R.id.logisticsRatingBar);
        saveTextView = (AppCompatTextView) findViewById(R.id.saveTextView);
        saveTextView.setOnClickListener(this);
    }

    public void initData() {

    }

    public void initEven() {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PICK_IMAGE) {
                picUrls.setLength(0);
                ArrayList<String> imgPaths = data.getStringArrayListExtra(ImageSelectorActivity.EXTRA_RESULT);
                publishPicAndMessAdapter.setImages(imgPaths);
                setImageToView(imgPaths);
            }
        }
    }

    protected void setImageToView(List<String> imgPaths) {
        picSize = imgPaths.size();
        for (int i = 0; i < imgPaths.size(); i++) {
            Uri uri = Uri.fromFile(new File(imgPaths.get(i)));
            try {
                ContentResolver contentResolver = getContentResolver();
                InputStream is = contentResolver.openInputStream(uri);
                try {
                    is.reset();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 4;
                options.inJustDecodeBounds = false;
                Bitmap bitmap = BitmapFactory.decodeStream(is, null, options);
                uploadPic(bitmap);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    private void uploadPic(Bitmap bitmap) {
        final File temp = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), String.valueOf(System.currentTimeMillis() + ".png"));
        if (!temp.exists()) {
            try {
                temp.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(temp));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        RequestParams params = new RequestParams();
        try {
            params.put("file", temp);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        ApiOkHttp.excuteUpload(ApiOkHttp.UPLOAD_FILE, this, params, new OnRequestDataListener() {
            @Override
            public void requestSuccess(int code, JSONObject data) {
                try {
                    int code1 = data.getInt("code");
                    if (code1 == 200) {
                        picNum++;
                        String url = data.getString("data");
                        picUrls.append(url + ",");
                        if (picNum >= picSize) {
                            picNum = 0;
                            String regex = "^,*|,*$";
                            String str1 = picUrls.toString().trim().replaceAll(regex, "");
                            mLists.get(mCurrentPosition).setCommentImgUrl(str1);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void requestFailure(int code, String msg) {

            }
        });
    }

    @Override
    public void onClick(int position, PublishPicAndMessAdapter adapter) {
        publishPicAndMessAdapter = adapter;
        mCurrentPosition = position;
        mLists.get(mCurrentPosition).setOrderItemId(itemVoBeans.get(mCurrentPosition).getId());
        mLists.get(mCurrentPosition).setGoodsId(itemVoBeans.get(mCurrentPosition).getGoodsVo().getId());
    }

    @Override
    public void onTextChange(int position, AppCompatEditText editText, String text) {
        mCurrentPosition = position;
        mLists.get(mCurrentPosition).setCommentInfo(text);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.saveTextView:
                addComment();
                break;
            default:
                break;
        }
    }

    public void addComment() {
        com.alibaba.fastjson.JSONObject params = new com.alibaba.fastjson.JSONObject();
        params.put("co",mLists);
        params.put("orderNo",orderNo);
        ApiOkHttp.addComment(this, params, new OnRequestDataListener() {
            @Override
            public void requestSuccess(int code, JSONObject data) {
                try {
                    int code1 = data.getInt("code");
                    String msg = data.getString("msg");
                    ToastUtil.show(EvaluateActivity.this,msg);
                    if (code1 == 200) {
                        EvaluateActivity.this.finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Log.e("TAG", "requestSuccess: "+data.toString());
            }

            @Override
            public void requestFailure(int code, String msg) {

            }
        });
    }
}
